#!/usr/bin/env python

# (c) Copyright 2008 Paul Hankin. All Rights Reserved. 

from __future__ import with_statement

__import__('sys').path.append('..')

from StringIO import StringIO
import unittest

import jelly_data
import bg.importer

def import_jelly(f):
    return bg.importer.import_match(f, 'jelly')

class JellyIOTest(unittest.TestCase):
    def testReimport(self):
        "Check exporting jellyfish match and reimporting is idempotent."
        matches = [m for m in dir(jelly_data) if m.endswith('_match')]
        count = 0
        for jm in matches:
            match = import_jelly(StringIO(getattr(jelly_data, jm)))
            match_out = '\n'.join(match.export_jellyfish_mat())
            match_back = import_jelly(StringIO(match_out))
            match_out2 = '\n'.join(match_back.export_jellyfish_mat())
            self.assertEquals(match_out, match_out2)
            count += 1
        assert count > 3

    def testNoimportBad(self):
        "Check we can't import broken matches."
        matches = [m for m in dir(jelly_data) if m.endswith('_match_bad')]
        count = 0
        for jm in matches:
            f = StringIO(getattr(jelly_data, jm))
            self.assertRaises(bg.importer.ImportException,
                import_jelly, f)
            count += 1
        assert count > 0

    def testImport(self):
        "Check basic facts about imported jellyfish matches."
        match_names = [m[:-6] for m in dir(jelly_data) if m.endswith('_match')]
        matches, infos = [
            [getattr(jelly_data, m + suffix) for m in match_names]
            for suffix in ('_match', '_info')
        ]
        assert len(matches) == len(infos)
        assert len(matches) > 3
        for match_source, info in zip(matches, infos):
            match = import_jelly(StringIO(match_source))
            self.assertEquals(match.length, info['length'])
            self.assertEquals(len(list(match)), info['games'])
            self.assertEquals(len(list(match)), len(info['scores']))
            for game, score in zip(match, info['scores']):
                player, points = game.result
                if player: self.assertEquals(score, -points)
                else: self.assertEquals(score, points)
    
if __name__ == '__main__':
    unittest.main()
